<template>
  <div class="topnav" ref="Topnav">
    <router-link to="/" class="logo" ref="logo" @click="top">
      <svg class="icon">
        <use xlink:href="#icon-zeus"></use>
      </svg>
    </router-link>
    <ul class="menu">
      <router-link v-if="toggle" to="/doc">文档</router-link>
    </ul>
    <span
      v-if="toggleMenuButtonVisible"
      class="toggleAside"
      @click="toggleMenu"
    >
      <svg class="icon">
        <use xlink:href="#icon-menu"></use>
      </svg>
    </span>
  </div>
</template>
<script lang="ts">
import { inject, ref, onMounted, watchEffect, onUnmounted } from 'vue'

export default {
  setup(props) {
    const menuVisible = inject<ref<boolean>>('menuVisible') // get
    const Topnav = ref<HTMLDivElement>(null)
    const logo = ref<HTMLAnchorElement>(null)
    const top = () => {
      document.documentElement.scrollTo(0, 0)
    }
    const toggleMenu = () => {
      menuVisible.value = !menuVisible.value
    }
    const width = document.documentElement.clientWidth
    // 页面滚动式给Topnav添加样式
    const handleScroll = () => {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      if (scrollTop > 0 && width < 500) {
        Topnav.value.style.background = 'rgba(0,0,0,0.08)'
        Topnav.value.style.boxShadow = '3px 0 10px rgba(0,0,0,0.5)'
      } else {
        Topnav.value.style.background = 'unset'
        Topnav.value.style.boxShadow = 'unset'
      }
    }

    onMounted(() => {
      window.addEventListener('scroll', handleScroll)
      if (!props.toggle) {
        logo.value.$el.style.marginLeft = 'auto'
        logo.value.$el.style.marginRight = 'unset'
        console.log(logo.value.$el.style)
      }
    })
    // 组件销毁时清除监听滚动
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll)
    })
    return { toggleMenu, Topnav, logo, top }
  },
  props: {
    toggleMenuButtonVisible: {
      type: Boolean,
      default: false,
    },
    toggle: {
      type: Boolean,
      default: true,
    },
  },
}
</script>
<style lang="scss" scoped>
$color: #007974;
.topnav {
  color: $color;
  display: flex;
  padding: 10px 16px;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  justify-content: center;
  align-items: center;

  > .logo {
    max-width: 6em;
    margin-right: auto;
    > svg {
      width: 28px;
      height: 28px;
    }
  }
  > .menu {
    display: flex;
    white-space: nowrap;
    flex-wrap: nowrap;
    > li {
      margin: 0 1em;
    }
  }
  .toggleAside {
    display: inline-block;
    width: 24px;
    height: 24px;
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: none;
    > svg {
      width: 22px;
      height: 22px;
    }
  }
  @media (max-width: 500px) {
    .menu {
      display: none;
    }
    .logo {
      margin: 0 auto;
    }
    .toggleAside {
      display: block;
    }
  }
}
</style>
